﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using Microsoft.Devices;
using System.IO;
using System.Windows.Controls.Primitives;
using ThuPhap.Controls;
using System.ComponentModel;
using System.Threading;
using ThuPhap.Models;
using ThuPhap.Class;
using ThuPhap.ViewModels;
using Microsoft.Phone.Shell;
using System.Collections;


namespace ThuPhap
{
    public partial class StartPage : PhoneApplicationPage
    {
        ApplicationBarIconButton select;

        ApplicationBarIconButton delete;
        public StartPage()
        {
            
            //popup.IsOpen = true;
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(StartPage_Loaded);
            DataContext = App.StartPageViewModel;
            select = new ApplicationBarIconButton();
            select.IconUri = new Uri("/Resources/Images/appbar.select.rest.png", UriKind.RelativeOrAbsolute);
            select.Text = "select";
            select.Click += select_Click;
            

            delete = new ApplicationBarIconButton();
            delete.IconUri = new Uri("/Resources/Images/appbar.delete.rest.png", UriKind.RelativeOrAbsolute);
            delete.Text = "delete";
            delete.Click += delete_Click;
            //App.StartPageViewModel.FinishedReadGalleryEvent += new ViewModels.StartViewModel.FinishedReadGalleryDelegate(StartPageViewModel_FinishedReadGalleryEvent);
            
        }

        //void StartPageViewModel_FinishedReadGalleryEvent(int TotalItems)
        //{
        //    if (TotalItems > 6)
        //    {
        //        this.AllGalleryTextBlock.Visibility = Visibility.Visible;
        //    }
        //    else
        //    {
        //        this.AllGalleryTextBlock.Visibility = Visibility.Collapsed;
        //    }
        //}
        BackgroundWorker backgroundGallery, backgroundFile, backgroundStart;
        Thread thread;
        Popup popup = new Popup() { Child = new LoadingControl("Loading ..."), IsOpen = false };
        bool isLoading = false;
        void StartPage_Loaded(object sender, RoutedEventArgs e)
        {

            if ((!App.IsLoaded) && (!isLoading))
            {

                //popup.IsOpen = true;
                if (!App.StartPageViewModel.IsDataLoaded)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        App.FontViewModel.LoadData();
                    });
                    backgroundStart = new BackgroundWorker();
                    backgroundStart.DoWork += ((s, ev) => { App.StartPageViewModel.LoadData(); });
                    //thread = new Thread(new ThreadStart(App.StartPageViewModel.LoadData));
                    //thread.Start();
                }
                App.StartPageViewModel.GalleryItems.Clear();
                App.StartPageViewModel.StoredItems.Clear();
                backgroundGallery = new BackgroundWorker();
                backgroundGallery.DoWork += ((s, ev) =>
                {
                    isLoading = true;
                    
                    App.StartPageViewModel.UpdateGalleryItem();
                });
                
                backgroundGallery.RunWorkerCompleted += ((s, ev) =>
                {
                    //popup.IsOpen = false; 
                    //App.IsLoaded = true;
                    this.GalleryProgress.IsEnabled = false;
                    this.GalleryProgress.Visibility = Visibility.Collapsed;
                });

                backgroundFile = new BackgroundWorker();
                backgroundFile.DoWork += ((s, ev) =>
                {
                    isLoading = true;
                    App.StartPageViewModel.UpdateStoredItem();
                });

                backgroundFile.RunWorkerCompleted += ((s, ev) =>
                {
                    //popup.IsOpen = false; 
                    //App.IsLoaded = true;
                    SavePictureInfo savePicture = new SavePictureInfo();
                    var storedItems = savePicture.GetFileNames();
                    if (storedItems.Length > 0)
                    {
                        if (PanoramaControl.SelectedIndex == 3)
                            this.ApplicationBar.IsVisible = true;
                    }
                    this.FileProgress.IsEnabled = false;
                    this.FileProgress.Visibility = Visibility.Collapsed;
                });

                try
                {
                    backgroundStart.RunWorkerAsync();
                    backgroundFile.RunWorkerAsync();
                    backgroundGallery.RunWorkerAsync();
                }
                catch { }

            }

        }

        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int index = CreateListBox.SelectedIndex;
            if (index != -1)
            {
                switch (index)
                {
                    case 0:
                        NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                        break;
                    case 1:
                        NavigationService.Navigate(new Uri("/ListTemplatesPage.xaml", UriKind.Relative));
                        break;
                    case 2:
                        NavigationService.Navigate(new Uri("/ListOnlineTemplatesPage.xaml", UriKind.Relative));
                        break;
                    case 3://Open camera
                        CameraCaptureTask camera = new CameraCaptureTask();
                        camera.Show();

                        camera.Completed += new EventHandler<PhotoResult>(camera_Completed);
                        break;
                    default:
                        break;
                }
                CreateListBox.SelectedIndex = -1;
            }
        }


        void camera_Completed(object sender, PhotoResult e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                if (e.ChosenPhoto != null)
                {
                    ChooseImage.PhotoStream = e.ChosenPhoto;
                    NavigationService.Navigate(new Uri("/ChooseImage.xaml?camera=t", UriKind.Relative));
                }
            });

        }

        private void GalleryListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int index = GalleryListBox.SelectedIndex;
            if (index != -1)
            {
                GalleryItem item = GalleryListBox.SelectedItem as GalleryItem;
                NavigationService.Navigate(new Uri("/DetailPage.xaml?filename=" + item.Name, UriKind.Relative));
                GalleryListBox.SelectedIndex = -1;
            }
        }

        private void StoredItemListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //if (StoredItemListBox.SelectedIndex!=-1)
            //{
            //    var fileItem = StoredItemListBox.SelectedItem as FileViewModel;
            //    NavigationService.Navigate(new Uri("/MainPage.xaml?type=edit&filename=" + fileItem.Name, UriKind.Relative));
            //    StoredItemListBox.SelectedIndex = -1;
            //}
            MultiselectList target = (MultiselectList)sender;
            ApplicationBarIconButton i = (ApplicationBarIconButton)ApplicationBar.Buttons[0];

            if (target.IsSelectionEnabled)
            {

                if (target.SelectedItems.Count > 0)
                {
                    i.IsEnabled = true;
                }
                else
                {
                    i.IsEnabled = false;
                }
            }
            else
            {
                i.IsEnabled = true;
            }
        }

        private void StoredItemListBox_IsSelectionEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            while (ApplicationBar.Buttons.Count > 0)
            {
                ApplicationBar.Buttons.RemoveAt(0);
            }

            if ((bool)e.NewValue)
            {
                ApplicationBar.Buttons.Add(delete);
                ApplicationBarIconButton i = (ApplicationBarIconButton)ApplicationBar.Buttons[0];
                i.IsEnabled = false;

            }
            else
            {
                ApplicationBar.Buttons.Add(select);
            }
        }

        private void appbar_select_button_Click(object sender, EventArgs e)
        {
            StoredItemListBox.IsSelectionEnabled = true;
        }

        protected override void OnBackKeyPress(CancelEventArgs e)
        {
            base.OnBackKeyPress(e);
            if (StoredItemListBox.IsSelectionEnabled)
            {
                StoredItemListBox.IsSelectionEnabled = false;
                e.Cancel = true;
            }
        }

        void select_Click(object sender, EventArgs e)
        {
            StoredItemListBox.IsSelectionEnabled = true;
        }

        void delete_Click(object sender, EventArgs e)
        {
            IList source = StoredItemListBox.ItemsSource as IList;
            SavePictureInfo sp = new SavePictureInfo();
            while (StoredItemListBox.SelectedItems.Count > 0)
            {
                var item = (FileViewModel)StoredItemListBox.SelectedItems[0];
                source.Remove(item);
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    sp.RemoveFile(item.Name);
                });
            }
            if (source.Count == 0)
            {
                this.ApplicationBar.IsVisible = false;
            }
        }

        private void Panorama_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var panorama = sender as Panorama;
            if (panorama.SelectedIndex == 3)
            {
                if (App.StartPageViewModel.StoredItems.Count == 0)
                {
                    this.ApplicationBar.IsVisible = false;
                }
                else
                {
                    this.ApplicationBar.IsVisible = true;
                }
            }
            else
            {
                this.ApplicationBar.IsVisible = false;
            }
        }

        private void StackPanel_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            FileViewModel item = ((FrameworkElement)sender).DataContext as FileViewModel;
            if (StoredItemListBox.IsSelectionEnabled)
            {
                MultiselectItem container = StoredItemListBox.ItemContainerGenerator.ContainerFromItem(item) as MultiselectItem;
                if (container != null)
                {
                    container.IsSelected = !container.IsSelected;
                }
            }
            else
            {
                NavigationService.Navigate(new Uri("/MainPage.xaml?type=edit&filename=" + item.Name, UriKind.Relative));
            }
        }

        private void TemplateListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int index = TemplateListBox.SelectedIndex;
            if (index!=-1)
            {
                NavigationService.Navigate(new Uri("/PreviewTemplatePage.xaml?index=" + index, UriKind.Relative));
                TemplateListBox.SelectedIndex = -1;
            }
        }

        private void OnlineTemplateListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int index = OnlineTemplateListBox.SelectedIndex;
            if (index != -1)
            {

                NavigationService.Navigate(new Uri("/PreviewOnlineTemplatePage.xaml?index=" + index, UriKind.Relative));
                TemplateListBox.SelectedIndex = -1;
            }
        }
    }
}